#15章网络编程
import socket
import os

fileDir = 'D:/workspace/python/learnpy/iofile/'

#client TCP

def joinFile(fileName):
	return os.path.join(fileDir,fileName)

ip='www.sina.com.cn'
port = 80

#(socket.AF_INET, socket.SOCK_STREAM)
sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #Ipv4协议,tcp编程
sk.connect((ip,port)) #参数要传入一个tuple

# 发送数据: 要求返回新浪的首页内容 发送的数据必须是byte类型
cnt = 'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n'
sk.send(cnt.encode('utf-8'))

bufers = []

maxByte = 1024; #每次接收的最大字节数
count = 0;
while True:	
	d = sk.recv(maxByte)
	if d:
		bufers.append(d)
		count+=1
		print('第%s次接收...d='%str(count),'长度=',len(d))
	else:
		break

data = b''.join(bufers)

sk.close()

header,html = data.split(b'\r\n\r\n',1)

print(header.decode('utf-8'))
print('html len=',len(html))

with open(joinFile('sina.html'),'wb') as f:
	f.write(html)










